package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        //1、获取日期数据
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (begin.isBefore(end)) {
            begin = begin.plusDays(1);
            //新的数据放到集合
            dateList.add(begin);
        }

        //2、营业额数据
        List<Double> turnoverList = new ArrayList<>();
        //查每一天的营业额，并放到turnoverList
        for (LocalDate date : dateList) {
            //构建一天的开始时间，结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询这一天订单状态为完成的营业总额
            Map<String, Object> map = new HashMap<>();
            map.put("status", Orders.COMPLETED);
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);

            Double turnover = ordersMapper.sumByMap(map);
            turnover = turnover == null ? 0 : turnover;
            //将营业额数据放到集合中
            turnoverList.add(turnover);
        }


        //3、将数据封装为VO并返回
        TurnoverReportVO reportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();


        return reportVO;
    }

    @Override
    public UserReportVO getUsers(LocalDate begin, LocalDate end) {
        //1、获取日期数据
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (begin.isBefore(end)) {
            begin = begin.plusDays(1);
            //新的数据放到集合
            dateList.add(begin);
        }


        //2、获取用户总量和每日用户新增数量
        List<Integer> totalUsers = new ArrayList<>();
        List<Integer> newUsers = new ArrayList<>();

        for (LocalDate date : dateList) {
            //开始
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            //结束
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //当天之前的用户总量
            //select count(*) from user where create_time <=endTime
            Integer totalUser = getUserCount(null, endTime);

            //当天新增的用户量
            //select count(*) from user where create_time <=endTime and create_time >= beginTime
            Integer newUser = getUserCount(beginTime, endTime);
            //放到集合中
            totalUsers.add(totalUser);
            newUsers.add(newUser);

        }

        //3、封装为VO返回
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUsers, ","))
                .totalUserList(StringUtils.join(totalUsers, ","))
                .build();
    }

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //1、获取日期列表
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (begin.isBefore(end)) {
            begin = begin.plusDays(1);
            //新的数据放到集合
            dateList.add(begin);
        }

        //2、获取范围内每天的，订单总数，有效订单总数
        List<Integer> orderCountList = new ArrayList<>();//每天订单总数
        List<Integer> validOrderCountList = new ArrayList<>();//每天有效订单总数

        for (LocalDate date : dateList) {
            //开始
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            //结束
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //从数据库中获取当天的订单数据
            //每天总订单  select count(id) from orders where order_time>=beginTime and order_time<=endTime
            Integer orderCount = getOrderCount(beginTime, endTime, null);
            //每天有效总订单  select count(id) from orders where order_time>=beginTime and order_time<=endTime and status=5
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            //保存到集合中
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }


        //3、订单总数，有效订单总数，完成率 的数据
        //Integer sum = Stream.of(1, 2, 3, 4, 5).reduce(Integer::sum).get(); //15

        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();//订单总数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();//有效订单总数
        //完成率
        double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount.doubleValue();
        }

        //4、封装数据到VO
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        //1 先把时间区间转换好
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //2 查询数据库得到数据
        List<GoodsSalesDTO> goodsSalesDTOS = ordersMapper.getSalesTop10(beginTime, endTime);

        //3 把查询的数据进行封装VO 返回
        //nameList:  菜品1,菜品2,xx,xx,xx
        //GoodsSalesDTO ==>String
        //将集合中对象转换为商品的名称
        List<String> names = goodsSalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");
        //numberList 10,20,1,xx,xx,xx
        //将集合中对象转换为商品的分数
        List<Integer> numbers = goodsSalesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1、构建时间范围
        LocalDateTime beginTime = LocalDateTime.of(LocalDate.now().minusDays(30), LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(LocalDate.now().minusDays(1), LocalTime.MAX);
        //3、查询运营数据
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);

        //4、把数据填充到表格模板中，发送到前端
        InputStream in = this.getClass()
                .getClassLoader()
                .getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(in);

            XSSFSheet sheet = xssfWorkbook.getSheet("Sheet1");
            //拿行数据
            //拿单元格，然后将数据填充到单元格中
            sheet
                    .getRow(1)//行
                    .getCell(1)//单元格
                    .setCellValue("时间：" + beginTime.toLocalDate() + " 至 " + endTime.toLocalDate());
            //填充基础数据
            XSSFRow row3 = sheet.getRow(3);
            row3.getCell(2).setCellValue(businessData.getTurnover());//营业额
            row3.getCell(4).setCellValue(businessData.getOrderCompletionRate());//订单完成率
            row3.getCell(6).setCellValue(businessData.getNewUsers());//新增用户数

            XSSFRow row4 = sheet.getRow(4);
            row4.getCell(2).setCellValue(businessData.getValidOrderCount());//有效订单
            row4.getCell(4).setCellValue(businessData.getUnitPrice());//平均客单价

            for (int i = 0; i < 30; i++) {
                endTime = LocalDateTime.of(beginTime.toLocalDate(), LocalTime.MAX);
                BusinessDataVO oneDayData = workspaceService.getBusinessData(beginTime, endTime);
                log.info("{}到{}的数据：{}", beginTime, endTime, oneDayData);
                //填充到表格
                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(beginTime.toLocalDate() + "");
                row.getCell(2).setCellValue(oneDayData.getTurnover());
                row.getCell(3).setCellValue(oneDayData.getValidOrderCount());
                row.getCell(4).setCellValue(oneDayData.getOrderCompletionRate());
                row.getCell(5).setCellValue(oneDayData.getUnitPrice());
                row.getCell(6).setCellValue(oneDayData.getNewUsers());

                //日期时间要往后+1天
                beginTime = beginTime.plusDays(1);
            }

            //将单元格数据写到response中的输出流。
            ServletOutputStream out = response.getOutputStream();
            xssfWorkbook.write(out);//将数据写到网络流中

            //释放资源
            out.flush();
            out.close();
            xssfWorkbook.close();

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    private Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        Map<String, Object> map = new HashMap<>();
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("status", status);


        return ordersMapper.countByMap(map);
    }

    private Integer getUserCount(LocalDateTime beginTime, LocalDateTime endTime) {
        Map<String, Object> map = new HashMap<>();
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);

        return userMapper.countByMap(map);
    }


}
